package com.wwd.movie.login.filter;

import cn.hutool.json.JSONObject;
import com.wwd.movie.common.UserContext;
import com.wwd.movie.common.service.TokenService;
import com.wwd.movie.login.domain.dto.LoginUser;
import com.wwd.movie.login.domain.entity.MovieUser;
import com.wwd.movie.login.mapper.MovieUserMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private MovieUserMapper movieUserMapper;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                JSONObject payload = tokenService.parseToken(token);
                Long userId = payload.getLong("userId");
                String username = payload.getStr("username");
                // 查询数据库获取完整用户信息
                MovieUser user = movieUserMapper.selectById(userId);
                if (user != null) {
                    UserContext.setUser(user); // 放入上下文
                    UsernamePasswordAuthenticationToken auth =
                            new UsernamePasswordAuthenticationToken(
                                    new LoginUser(user), null, Collections.emptyList());
                    SecurityContextHolder.getContext().setAuthentication(auth);
                }
            } catch (Exception e) {
                // token无效或过期，可以忽略，后续 Security 会拦截
                // 日志记录 Token 解析错误
                logger.error("Token解析失败: " + e.getMessage());
            }
        }
        try {
            filterChain.doFilter(request, response);
        } finally {
            UserContext.clear(); // 防止内存泄漏
        }
    }
}
